import Vue from 'vue'
import Vuex, { Store } from 'vuex'

Vue.use(Vuex)
let shoppingList = window.sessionStorage.getItem('shoppingList')
let cartList = window.sessionStorage.getItem('cartList')
let store = new Vuex.Store({
  state: {
    shoppingList: shoppingList? JSON.parse(shoppingList):[],
    cartList:  cartList? JSON.parse(cartList):[],
  },
  mutations: {
    setShoppingList(state,data) {
      state.shoppingList = data;
    },
    addToCart({cartList},data) {
      let index = cartList.findIndex((v) => {
        return v.data.id === data.data.id;
      })
      if(index === -1) {
        cartList.push(data)
      } else {
        cartList[index].count++
      }
      console.log(cartList)
    },
    // 设置商品数量
    setCount({cartList}, {num,id}) {
      cartList.forEach((v,i) => {
        if(v.data.id === id) {
          if(v.count=== 0 && num === -1) {
            cartList.splice(i,1)
          } else {
            v.count +=num;
          }
        }
      })
    }
  },
  actions: {
  },
  modules: {
  }
})
store.subscribe((mutations, state) => {
  if(state.shoppingList) {
    window.sessionStorage.setItem('shoppingList', JSON.stringify(state.shoppingList))
  }
  if(state.cartList) {
    window.sessionStorage.setItem('cartList', JSON.stringify(state.cartList))
  }
})
export default store;